<script setup lang="ts">
import { useStore } from 'vuex'
import { onMounted, reactive, ref } from 'vue'
import { getFriendApplyList } from '../api/friend'
import { responseFriendApply } from '../utils/webSocketUtil'

const store = useStore()
const userId = store.getters.getUserId

const friendApplyInfo = reactive({
  id: 0,
  userId: 0,
  applier: 0,
  receiver: 0,
  nickname: '',
  avatar: '',
  status: '',
  applyTime: ''
})

const friendApplyList = ref(Array(friendApplyInfo))

onMounted(() => {
  getFriendApplyList(userId).then((res) => {
    friendApplyList.value = res.data as any
  })
})

const handleApplyFriend = (index: number, applier: number, receiver: number, status: string) => {
  responseFriendApply([applier, receiver, status], store)

  friendApplyList.value[index].status = status
}
</script>

<template>
  <div class="w-full h-9 flex items-start pl-5 pr-5">
    <caption class="caption-top text-lg mb-4 font-sans subpixel-antialiased text-gray-500">
      好友申请
    </caption>
  </div>
  <el-divider />
  <table class="table-auto w-full h-full">
    <tbody class="w-full h-full overflow-y-auto flex flex-col" style="max-height: 635px">
      <div v-for="(item, index) in friendApplyList" :key="index" class="w-3/4 ml-auto mr-auto">
        <tr class="w-full h-20 flex flex-row justify-between items-center">
          <div>
            <td>
              <img
                :src="item.avatar"
                class="w-14 h-14 rounded-full mr-3 object-scale-down border"
              />
            </td>
            <td class="pl-3 text-base font-sans subpixel-antialiased align-middle">
              {{ item.nickname }}
            </td>
          </div>
          <td>
            <span v-if="item.receiver === item.userId && item.status !== '1'" class="mr-5">
              待同意
            </span>
            <div v-if="item.status === '0' && item.receiver !== item.userId">
              <el-button
                type="success"
                @click="handleApplyFriend(index, item.applier, item.receiver, '1')"
                >同意
              </el-button>
              <el-button @click="handleApplyFriend(index, item.applier, item.receiver, '2')"
                >忽略</el-button
              >
            </div>
            <span v-if="item.status === '1'" class="text-gray-400 mr-5">已接受</span>
            <span
              v-if="item.status === '2' && item.receiver !== item.userId"
              class="text-gray-400 mr-5"
              >已忽略</span
            >
          </td>
        </tr>
        <el-divider />
      </div>
    </tbody>
  </table>
</template>

<style scoped>
.el-divider--horizontal {
  margin: 0;
}
</style>
